import router from "@/router";
import store from "@/store";
import sysConfig from "@/config";
import whiteList from "@/routerInterceptor/whiteList";
import { clearStorageData, setDataToVuex, isEmptyObject } from "@/tools";
import { flatTreeData } from "@/utils";
//路由白名单
router.beforeEach(async (to, from, next) => {
  let { path: toPath } = to;
  if (whiteList.includes(toPath)) {
    next();
    return;
  }
  //页面不存在
  //   let flatData = flatTreeData(routes, "children");
  //   let hasRoute = flatData.find((v) => v.path == toPath);
  //   if (!hasRoute) {
  //     next({
  //       path: "/NotFound",
  //       replace: true,
  //     });
  //     return;
  //   }
  //无有效登录信息
  let loginData = JSON.parse(localStorage.getItem("LOGIN_DATA") || "{}");
  if ((isEmptyObject(loginData) || !loginData) && !isLogin(toPath)) {
    next({
      path: "/login",
      replace: true,
    });
    return;
  }
  //登录页=》清楚所有缓存数据(vuex & storage)
  if (isLogin(toPath)) {
    clearStorageData();
  } else {
    //监听页面刷新
    let pageRefresh = localStorage.getItem("PAGE_REFRESH");
    if (pageRefresh && !store.state.PAGE_REFRESH) {
      setDataToVuex();
      let currentTanent = store.state.TENANT;
      //租户列表
      let tenantData = await store.dispatch("queryTenantData");
      if (
        !currentTanent ||
        !flatTreeData(tenantData, "child").find(
          (v) => v.tenantCode == currentTanent.tenantCode
        )
      ) {
        //无有效租户信息-返回登录页
        next({
          path: "/login",
          replace: true,
        });
        return;
      }
      //租户对应项目列表
      if (currentTanent && !isEmptyObject(currentTanent)) {
        await store.dispatch("queryTenantProjectSourceData");
      } else {
        next({
          path: "/login",
          replace: true,
        });
        return;
      }
      await store.dispatch("queryPermissionData");
    }
  }
  //系统标识
  let sysFlag = getLoginFlag(toPath);
  let $s = to.query.$s;
  if (!isLogin(toPath)) {
    if (!$s) {
      addRouterSysFlag(next, to);
    } else {
      if ($s == sysFlag) {
        next();
      } else {
        addRouterSysFlag(next, to);
      }
    }
  } else {
    next();
  }
});

//是否是登录页
function isLogin(toPath = "") {
  return toPath.endsWith("/login");
}

//获取系统登陆标识
function getLoginFlag(path = "/login") {
  let flag = path.split("/login")[0];
  if (flag in sysConfig) {
    return flag;
  }
  return "0";
}

//router添加系统标识
function addRouterSysFlag(next, to = {}) {
  let { path } = to;
  //系统标识
  let sysFlag = getLoginFlag(path);
  next &&
    next({
      ...to,
      query: {
        ...to.query,
        $s: sysFlag,
      },
    });
}
